package org.study.redis.boot.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

/**
 * 基于 Redis 的延迟队列示例
 *
 * @author doveylovey
 * @version v1.0.0
 * @email 1135782208@qq.com
 * @date 2024年05月06日
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/delay")
public class DelayQueueController {
    private String DELAY_QUEUE_KEY = "myDelayQueue";
    private final RedisTemplate<String, String> redisTemplate;

    @GetMapping("/enqueue")
    public String enqueue(@RequestParam String msg, @RequestParam long delaySeconds) {
        long score = System.currentTimeMillis() / 1000 + delaySeconds;
        redisTemplate.opsForZSet().add(DELAY_QUEUE_KEY, msg, score);
        log.info("发送消息成功，message={}，delaySeconds={}", msg, delaySeconds);
        return "发送消息成功";
    }

    @Scheduled(fixedRate = 5000)
    public void dequeue() {
        Set<String> msgSet = redisTemplate.opsForZSet().rangeByScore(DELAY_QUEUE_KEY, 0, System.currentTimeMillis() / 1000);
        if (CollectionUtils.isNotEmpty(msgSet)) {
            msgSet.forEach(msg -> {
                redisTemplate.opsForZSet().remove(DELAY_QUEUE_KEY, msg);
                log.info("消费消息：" + msg);
            });
        }
    }
}